package ph.com.gs3.formalistics.model.facades;

import org.json.JSONException;

import ph.com.gs3.formalistics.model.LocalDataAccessObject.InsertFailedException;
import ph.com.gs3.formalistics.model.ldao.FormTableReferenceLDAO;
import ph.com.gs3.formalistics.model.ldao.FormsLDAO;
import ph.com.gs3.formalistics.model.vo.business.form.Form;
import ph.com.gs3.formalistics.model.vo.business.form.FormFieldData.InvalidFormFieldException;
import android.content.Context;
import android.database.SQLException;

public class FormsDataWriter {

	public static final String TAG = FormsDataWriter.class.getSimpleName();

	protected FormTableReferenceLDAO formTableReferenceLDAO;
	protected FormsLDAO formsLDAO;

	public FormsDataWriter(Context context) {
		formTableReferenceLDAO = new FormTableReferenceLDAO(context);
		formsLDAO = new FormsLDAO(context);
	}

	public Form saveForm(Form form) {
		Form updatedOrSavedForm = null;

		formsLDAO.open();

		try {
			// Throws JSONException, InvalidFormFieldException
			Form oldForm = formsLDAO.getForm(form.getWebId(), form.getCompany().getId());

			if (oldForm != null) { // This form is already existing, update it
				// Throws JSONException, InvalidFormFieldException
				updatedOrSavedForm = formsLDAO.updateForm(form);
				formsLDAO.updateFormTable(updatedOrSavedForm);
			} else {
				int formDbId = formsLDAO.insertForm(form);

				// Throws JSONException, InvalidFormFieldException
				updatedOrSavedForm = formsLDAO.getForm(formDbId);
				formsLDAO.createFormTable(updatedOrSavedForm);

				// Save a reference to the table
				try {
					formTableReferenceLDAO.open();
					formTableReferenceLDAO.saveTableName(formDbId,
					        updatedOrSavedForm.getGeneratedFormTableName());
				} catch (InsertFailedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					formTableReferenceLDAO.close();
				}

			}
		} catch (JSONException | InvalidFormFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			formsLDAO.close();
		}
		return updatedOrSavedForm;

	}
}
